"""
支付宝支付
"""
import traceback

from alipay import AliPay

app_private_key_string = open("pay/private.txt").read()
alipay_public_key_string = open("pay/public.txt").read()
RETURN_URL = 'http://localhost:8000/goods/get_pay_result'


class AliPayView(object):
    """
    封装阿里支付
    """

    def __init__(self, app_notify_url=None, sign_type='RSA2', debug=True, notify_url=RETURN_URL, return_url=RETURN_URL):
        self.app_id = "2021000119693860"
        self.sign_type = sign_type
        self.app_notify_url = app_notify_url
        self.debug = debug
        self.alipay = self.get_alipay_obj()
        self.notify_url = notify_url
        self.return_url = return_url

    def get_alipay_obj(self):
        """
        实例化对象
        """
        alipay = AliPay(
            appid=self.app_id,
            app_notify_url=self.app_notify_url,  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type=self.sign_type,  # RSA 或者 RSA2
            debug=self.debug  # 默认False
        )
        return alipay

    def get_pay_url(self, order_id, price, subject='收费'):
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        try:
            order_str = self.alipay.api_alipay_trade_page_pay(
                subject=subject,
                out_trade_no="%s" % order_id,  # 订单号  注意，标准的json格式没有 '' 单引号，只有 "" 双引号，python默认为 '' 单引号
                total_amount=price,  # 订单价格
                return_url=self.return_url,
                notify_url=self.notify_url
            )

            # 生成支付链接
            # self._gateway = "https://openapi.alipaydev.com/gateway.do"
            request_url = self.alipay._gateway + '?' + order_str
            return request_url
        except:
            error = traceback.format_exc()
            print('Alipay error:{}'.format(error))
            return False

    def get_pay_result(self, order_id):
        """
        检查订单支付结果
        """
        response = self.alipay.api_alipay_trade_query(out_trade_no=order_id)
        return response
